package com.example.hfweather.util

import com.example.hfweather.WeatherApplication
import com.example.hfweather.WeatherGlobal
import com.example.hfweather.apis.ApiService
import com.example.hfweather.storage.TokenPreferences
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object RetrofitClient {


    /*可以复用在项目中，替换基地址*/
//    定义基础地址
    private  var BASE_URL = WeatherGlobal.getBaseUrl()

    //创建okHttpClient实例

     private val okHttpClient: OkHttpClient by lazy {
         OkHttpClient.Builder()
             .addInterceptor(AuthInterceptor)
             .addInterceptor(//添加日志拦截器
                 HttpLoggingInterceptor()
                     .setLevel(HttpLoggingInterceptor.Level.BODY))
             .connectTimeout(20, TimeUnit.SECONDS)
             .readTimeout(20, TimeUnit.SECONDS)
             .build()


     }
    //创建一个token拦截器
    private val AuthInterceptor = object : Interceptor {

        override fun intercept(chain: Interceptor.Chain): Response {
            //1.获取本次网络请求对象
            val request = chain.request()
           // 2.获取本地token
            val token = TokenPreferences.getInstance(WeatherApplication.getInstance()).getToken()
            //3.携带 token
            val newRequest = token?.let {
                request.newBuilder()
                    .addHeader("Authorization", "Bearer $it")
                    .build()
            }?: request
            //4.发送请求
            return chain.proceed(newRequest)
        }
    }

    //    2.创建Retrofit实例（延时初始化）
//    确保第一次需要使用ApiService时才创建实例对象，避免不必要的开销
    val apiService : ApiService by lazy {
        Retrofit.Builder()//创建Retrofit实例
            .client(okHttpClient)
            .baseUrl(BASE_URL)//设置基础地址
            .addConverterFactory(GsonConverterFactory.create())//添加转换器 GSON数据解析
            .build()//创建Retrofit实例
            .create(ApiService::class.java)//创建ApiService实例
    }
}